import { filterAuth, getDicByKey } from '@/support/common';
import { ExportOutlined } from '@ant-design/icons';
import { Button, Card, message, Popconfirm, Image } from 'antd';
import { connect } from 'dva';
import React, { PureComponent } from 'react';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import { getMd5 } from '@/utils/utils';
import { downloadBlobFileByURL } from '@/services/downloadURLFile';
import { fingerprintFetch } from '@/utils/request';
const shuttingStateHash = {
  0: '锁止',
  1: '未锁止',
};
const testTypeHash = {
  0: '初始测试',
  1: '复测',
};
const expirationStateHash = {
  0: '有效',
  1: '无效',
};
const detectionResultHash = {
  0: '有效呼气，呼气测试通过',
  1: '有效呼气，呼气测试失败',
  2: '有效呼气，呼气测试通过，但有警告',
  3: '无效呼气，一般错误',
  4: '无效呼气，用户结束吹气太早',
  5: '无效呼气，用户吹气太轻',
  6: '无效呼气，用户吹气过猛',
  7: '无效呼气，笼统地说明呼气样本不可接受',
  8: '无效呼气，测试期结束',
  9: '无感检测通过',
  10: '无感检测失败',
};
const faceRecognitionResultHash = {
  0: '未获取到人脸识别结果',
  1: '未检测到人脸',
  2: '检测到已注册人脸',
  3: '检测到未注册人脸',
};
const finalResultHash = {
  0: '综合判断合格',
  1: '综合判断不合格',
};
const mapStateToProps = (state: any) => ({
  recordQuery: state.recordQuery,
  loading: state.loading.effects['recordQuery/getFetchPage'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});
class RecordQuery extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
      detailVisible: false,
      detailData: {},
      exportLoading: false,
      previewVisible: false,
      previewImage:'',
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'recordQuery/getFetchPage',
      payload: { url: '/msalcohollock/record/page' },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'recordQuery/initData',
    });
  }

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    // dispatch({
    //   type: 'recordQuery/getFetchPage',
    //   payload: { url: '/msalcohollock/record/page', ...formValues },
    // });
  };

  handleDownload = (strUrl: any, name: any) => {
    if (strUrl === null || strUrl === '') {
      message.error('文件缺失，无法下载！');
      return;
    }

    const http = strUrl.split('?')[0];
    const files = http.split('/');
    const fileName = files[files.length - 1];
    name = `${name}.${fileName}`;
    const str = `${window.g.url}/common/download?strUrl=` + strUrl;
    let md5 = getMd5('strUrl=' + strUrl);
    const newOptions: any = {};
    newOptions.method = 'GET';
    newOptions.headers = {
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    fingerprintFetch(str, newOptions)
      .then(response => {
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display = 'none';
        aLink.href = window.URL.createObjectURL(blob);
        aLink.download = name;
        aLink.click();
        document.body.removeChild(aLink);
      })
      .catch(() => message.error('下载失败，请稍后在试!'));
  };

  // 暂停其它音频播放
  pauseOther = (event: any) => {
    let audios = document.getElementsByName('commentAudio');
    audios.forEach((item: any) => {
      if (item !== event.currentTarget) {
        item.pause();
      }
    });
    event.stopPropagation();
    event.preventDefault();
  };

  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'recordQuery/delDataWithRes',
      payload: { url: '/userfeedback/batchdeleteusercomment?sid=' + sid },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          message.success('操作成功！');
          this.handleFlushPage();
        }
      },
    });
  };

  handleBatchDelete = (key: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'recordQuery/delDataWithRes',
      payload: { url: '/userfeedback/batchdeleteusercomment?sid=' + key.join(',') },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          message.success('操作成功！');
          this.handleFlushPage();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
    });
  };

  viewDetail = (record: any) => {
    const { dispatch, projectOptions, dicData } = this.props;
    dispatch({
      type: 'recordQuery/getDataWithRes',
      payload: { url: '/userfeedback/usercommentfinddetail', sid: record.id },
      callback: (resp: any) => {
        if (resp.statusCode === '0') {
          let newData = { ...resp.data };
          let curOptions = projectOptions.filter((item: any) => item.value === record.projectId);
          if (curOptions && curOptions.length > 0) {
            newData.projectName = curOptions[0].label;
          }
          newData.feedbackTypeName = getDicByKey(dicData, 'feedbackType', record.feedbackType);
          newData.feedbackSourceType =
            record.feedbackSourceType == 'dfspt' ? '' : record.feedbackSourceType;
          newData.typeSourcesName =
            record.typeSources == 'dfspt'
              ? ''
              : getDicByKey(dicData, 'commentTypeSources', record.typeSources);
          this.setState({ detailVisible: true, detailData: newData });
        }
      },
    });
  };

  changeVisible = () => {
    this.setState({ detailVisible: false, detailData: {} });
  };

  handleExport = () => {
    const { formValues } = this.state;
    const { dispatch } = this.props;
    const {
      recordQuery: {
        pageData: { pagination },
      },
    } = this.props;
    if (pagination.total > 5000) {
      message.warning('您目前搜索的结果等于0条或者大于5000条，请选择查询条件，精确查询范围！');
      return;
    }
    const params = formValues;
    downloadBlobFileByURL(
      '/msalcohollock/record/export',
      { method: 'post', data: params },
      `导出记录${new Date().toLocaleDateString()}`,
    );
  };

  formatFormvalues = (values: any) => {
    const nweVals = { ...values };
    if (values.dataCollectionDate) {
      const collectTimes = values.dataCollectionDate.map(
        (t: any) => t.format('YYYY-MM-DD HH:mm:ss') ?? '',
      );
      nweVals.collectStartTime = collectTimes[0];
      nweVals.collectEndTime = collectTimes[1];
      delete nweVals.dataCollectionDate;
    }
    if (values.systemDate) {
      const systemTimes = values.systemDate.map((t: any) => t.format('YYYY-MM-DD HH:mm:ss') ?? '');
      nweVals.systemStartTime = systemTimes[0];
      nweVals.systemEndTime = systemTimes[1];
      delete nweVals.systemDate;
    }
    return nweVals;
  };

  //查看照片
  showPhoto = (record: any) => {
    this.setState({
      previewImage: record.facePicture ?? '',
      previewVisible: true,
    });
  };
  render() {
    const {
      recordQuery: {
        pageData: { list, pagination },
      },
      loading,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, selectedRowKeys, previewVisible, previewImage } = this.state;
    const isExport = filterAuth('recordQuery_doExport', permissions, pathname);
    const columns = [
      {
        title: '记录编码',
        dataIndex: 'code',
      },
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: '控制盒编号',
        dataIndex: 'cboxCode',
      },
      {
        title: '手持机锁止状态',
        dataIndex: 'shuttingState',
        render: (text: any) => shuttingStateHash[text],
      },
      {
        title: '手持机测试类型',
        dataIndex: 'testType',
        render: (text: any) => testTypeHash[text],
      },
      {
        title: '提供的呼气是否有效',
        dataIndex: 'breathState',
        render: (text: any) => expirationStateHash[text],
      },
      {
        title: '手持机的检测结果',
        dataIndex: 'detectionResult',
        render: (text: any) => detectionResultHash[text],
      },
      {
        title: '人脸识别结果',
        dataIndex: 'faceRecognitionResult',
        render: (text: any) => faceRecognitionResultHash[text],
      },
      {
        title: '人脸照片',
        dataIndex: 'facePicture',
        render: (text: any, record: any) => {
          return text ? (
            <a
              onClick={() => {
                this.showPhoto(record);
              }}
            >
              <div>查看</div>
            </a>
          ) : (
            ''
          );
        },
      },
      {
        title: '最终结果',
        dataIndex: 'finalResult',
        render: (text: any) => finalResultHash[text],
      },
      {
        title: '系统时间',
        dataIndex: 'systemTime',
      },
      {
        title: '数据采集时间',
        dataIndex: 'collectTime',
      },
    ];
    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    }
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : page.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      // rowSelection: isDel ? rowSelection : null,
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any, index) => index,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '记录编码',
        key: 'code',
        customStyle: 8,
      },
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
        customStyle: 8,
        rules: [
          {
            required: false,
            message: '请输入英文及数字!',
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
        formItemProps: {
          normalize: (value, prevValue, prevValues) => {
            // 转大写
            return value.toUpperCase();
          },
        },
      },
      {
        type: 'rangePicker',
        title: '数据采集时间',
        key: 'dataCollectionDate',
        customStyle: 8,
      },
      {
        type: 'rangePicker',
        title: '系统时间',
        key: 'systemDate',
        customStyle: 8,
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'recordQuery/getFetchPage',
              url: '/msalcohollock/record/page',
            }}
            handleFieldsValue={this.formatFormvalues}
            saveFormValues={(val: any) => {
              this.setState({ formValues: Object.assign(formValues, val) });
            }}
            handleFormReset={() =>
              this.setState({
                formValues: {},
              })
            }
          />
        </Card>
        <Card className={styles.standardTable}>
          {/* {isDel || isExport ? ( */}
          <div className="my_newItem">
            {/* {isDel && selectedRowKeys.length > 0 ? (
                <>
                  <span>已选&nbsp;{selectedRowKeys.length}&nbsp;项&nbsp;&nbsp;&nbsp;&nbsp;</span>
                  <Popconfirm
                    title="是否确认删除所选数据？"
                    onConfirm={() => this.handleBatchDelete(selectedRowKeys)}
                  >
                    <Button size="small" type="primary" icon={<DeleteOutlined />} danger>
                      批量删除
                    </Button>
                  </Popconfirm>
                </>
              ) : null} */}
            {isExport ? (
              <Popconfirm title="是否确认导出数据？" onConfirm={() => this.handleExport()}>
                <Button
                  size="small"
                  icon={<ExportOutlined />}
                  type="primary"
                  loading={this.state.exportLoading}
                >
                  导出
                </Button>
              </Popconfirm>
            ) : null}
          </div>
          {/* ) : null} */}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'recordQuery/getFetchPage',
              url: '/msalcohollock/record/page',
            }}
            formValues={formValues}
            currentName= 'page'
            pageSizeName='size'
          />
        </Card>
        <Image
          width={200}
          style={{ display: 'none' }}
          // src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png?x-oss-process=image/blur,r_50,s_50/quality,q_1/resize,m_mfit,h_200,w_200"
          preview={{
            visible: previewVisible,
            src: previewImage,
            onVisibleChange: value => {
              this.setState({
                previewVisible: value,
              });
            },
          }}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(RecordQuery);
